<template>
  <div class="tag-bind-container">
    <div class="header">
      <div>
        <el-icon class="back-icon" @click="goBack">
          <ArrowLeft />
        </el-icon>
      </div>
      <div>
        {{ route.meta.title }}
      </div>
      <div></div>
    </div>

    <div class="form-container">
      <el-form :model="form" :rules="rules.value" class="bind-form" label-position="left">
        <el-form-item label="标签编号" label-width="80" prop="tagCode">
          <div style="color: #f56c6c; margin-bottom: 8px; font-size: 14px">请将标签靠近手机背面</div>
          <el-input v-model.trim="form.tagCode" :disabled="isUnbind ? false : isUnbind" class="full-width" clearable placeholder="请扫描标签编号" />
        </el-form-item>

        <template v-if="!isUnbind || (isUnbind && showDetailForm)">
          <el-form-item label="绑定目标" label-width="80" prop="bindTargetType">
            <el-radio-group v-model="form.bindTargetType" :disabled="isUnbind">
              <el-radio :value="1">假台车</el-radio>
              <el-radio :value="2">移车台</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="form.bindTargetType === 1" label="项目号" label-width="80" prop="projectId">
            <el-select
              v-model="form.projectId"
              :disabled="isUnbind"
              class="full-width"
              clearable
              filterable
              placeholder="请选择项目号"
              @change="onProjectChange"
            >
              <el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="form.bindTargetType === 1" label="车辆号" label-width="80" prop="vehicleCode">
            <el-input v-model.trim="form.vehicleColumn" :disabled="isUnbind" clearable placeholder="车列" style="width: 30%" type="text" />
            <span style="margin: 0px 20px">-</span>
            <el-input v-model.trim="form.vehicleNumber" :disabled="isUnbind" clearable placeholder="车辆" style="width: 30%" type="text" />
          </el-form-item>

          <el-form-item v-if="form.bindTargetType === 1" label="WBS" label-width="80" prop="wbsCode">
            <span>A-{{ form.projectCode }}-P-{{ form.vehicleColumn }}-{{ form.vehicleNumber }}</span>
          </el-form-item>

          <el-form-item v-if="form.bindTargetType === 1" label="标签位置" label-width="80" prop="tagPosition">
            <el-select v-model="form.tagPosition" :disabled="isUnbind" class="full-width" clearable placeholder="请选择标签位置">
              <el-option v-for="position in tagPositions" :key="position.value" :label="position.label" :value="position.value" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="form.bindTargetType === 1" label="车型" label-width="80" prop="carriageTypeId">
            <el-radio-group v-model="form.carriageTypeId" :disabled="isUnbind">
              <el-radio :value="'0'">中间车</el-radio>
              <el-radio :value="'1'">头车</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.bindTargetType === 1 && form.carriageTypeId === '1'" label="车头朝向" label-width="80" prop="carPositions">
            <el-select v-model="form.carPositions" :disabled="isUnbind" class="full-width" clearable placeholder="请选择车头朝向">
              <el-option v-for="position in carPositions" :key="position.value" :label="position.label" :value="position.value" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="form.bindTargetType === 2" label="移车台" label-width="80" prop="moveTheCar">
            <el-select v-model="form.moveTheCar" :disabled="isUnbind" class="full-width" clearable placeholder="请选择移车台">
              <el-option v-for="position in moveTheCarList" :key="position.value" :label="position.label" :value="position.value" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
    </div>

    <div class="button-container">
      <el-button :disabled="scanDisabled" :loading="scanLoading" class="scan-button" type="primary" @click="scanTag"> 扫描标签 </el-button>
      <el-button :loading="loading" class="submit-button" type="primary" @click="isUnbind ? handleUnbind() : handleSubmit()"> 确定 </el-button>
    </div>
  </div>
</template>

<script lang="ts" name="tagbind" setup>
// 声明window.Android、window.callJsFunction类型，避免TS报错
declare global {
  interface Window {
    Android?: {
      powerOn?: () => void;
      powerOff?: () => void;
      startRead?: () => void;
      readRfid?: () => void;
      stopRead?: () => void;
    };
    callJsFunction?: (jsonData: string) => void;
  }
}
import { TagbindFormData, TagbindPositions } from '@/api/tagbind/type';
import { bindTag, getTagProject, unbindTag, getTractionList } from '@/api/tagbind';
import { computed, watch } from 'vue';
// import type { Arrayable, FormItemRule } from 'element-plus';
import { useDict } from '@/utils/dict';

const router = useRouter();

const route = useRoute();

const form = ref<TagbindFormData>({
  id: '',
  tagCode: '',
  bindTargetType: 1,
  projectCode: '',
  projectId: '',
  vehicleCode: '',
  vehicleColumn: '',
  vehicleNumber: '',
  wbsCode: '',
  tagPosition: '',
  carriageTypeId: '0',
  carPositions: '',
  moveTheCar: ''
});

const loading = ref(false);
const scanLoading = ref(false);
const scanDisabled = ref(false);

const dictMap = useDict('painting_project_number');
const projectOptions = computed(() => dictMap['painting_project_number'] || []);

const tagPositions = ref<TagbindPositions[]>([
  { value: 'e', label: '东' },
  { value: 'w', label: '西' }
]);

const carPositions = ref<TagbindPositions[]>([
  { value: 'e', label: '朝东' },
  { value: 'w', label: '朝西' }
]);

const moveTheCarList = ref<TagbindPositions[]>([
  { value: '1', label: '移车台1' },
  { value: '2', label: '移车台2' },
  { value: '3', label: '移车台3' }
]);

//监听绑定目标类型变化，获取移车台列表
watch(
  () => form.value.bindTargetType,
  (val) => {
    if (val === 2) {
      getTractionList().then((res) => {
        if (res.code === 200 && res.data) {
          moveTheCarList.value = res.data.map((item: any) => ({
            value: item.workstationCode,
            label: item.workstationName
          }));
        }
      });
    }
  }
);

const isUnbind = computed(() => route.meta.title === '标签解绑');
const showDetailForm = ref(false);
const rules = computed<any>(() => {
  if (isUnbind.value) {
    return {
      tagCode: [{ required: true, message: '请扫描标签编号', trigger: 'change' }]
    };
  } else {
    return {
      tagCode: [{ required: true, message: '请扫描标签编号', trigger: 'change' }],
      bindTargetType: [{ required: true, message: '请选择绑定目标', trigger: 'change' }],
      projectId: [{ required: true, message: '请选择项目号', trigger: 'change' }],
      vehicleCode: [{ required: true, message: '请输入车辆号', trigger: 'blur' }],
      tagPosition: [{ required: true, message: '请选择标签位置', trigger: 'change' }],
      carriageTypeId: [{ required: true, message: '请选择车型', trigger: 'change' }],
      moveTheCar: [{ required: true, message: '请选择移车信息', trigger: 'change' }]
    };
  }
});

const goBack = () => {
  router.back();
};

const handleSubmit = async () => {
  if (!form.value.tagCode) {
    ElMessage.warning('请扫描标签编号');
    return;
  }
  if (form.value.bindTargetType == 1) {
    // 校验必填
    if (!form.value.projectId) {
      ElMessage.warning('请选择项目号');
      return;
    }
    if (!form.value.vehicleColumn || !form.value.vehicleNumber) {
      ElMessage.warning('请输入车辆号');
      return;
    }
    if (!form.value.tagPosition) {
      ElMessage.warning('请选择标签位置');
      return;
    }
    if (form.value.carriageTypeId == 1) {
      if (!form.value.carPositions) {
        ElMessage.warning('请选择车头朝向');
        return;
      }
    }
  } else {
    if (!form.value.moveTheCar) {
      ElMessage.warning('请选择移车信息');
      return;
    }
  }

  // 组装后端字段
  let submitData;
  if (form.value.bindTargetType == 1) {
    //假台车
    submitData = {
      id: form.value.id,
      tagCode: form.value.tagCode,
      bindTargetType: form.value.bindTargetType,
      projectCode: form.value.projectCode,
      projectId: form.value.projectId,
      vehicleCode: form.value.vehicleCode,
      vehicleColumn: form.value.vehicleColumn,
      vehicleNumber: form.value.vehicleNumber,
      wbsCode: form.value.wbsCode,
      tagLocation: form.value.tagPosition,
      vehicleType: form.value.carriageTypeId,
      carHeadOrientation: form.value.carPositions,
      moveTheCar: form.value.moveTheCar
    };
  } else {
    //移车台
    submitData = {
      tagCode: form.value.tagCode,
      bindTargetType: form.value.bindTargetType,
      workstationName: moveTheCarList.value.find((item) => item.value === form.value.moveTheCar)?.label || '',
      workstationCode: form.value.moveTheCar
    };
  }
  loading.value = true;
  try {
    const res = await bindTag(submitData);
    if (res.code == 200) {
      ElMessage.success('绑定成功');
      router.back();
    } else {
      ElMessage.warning(res.msg || '绑定失败');
    }
  } catch (e) {
    //检测异常
    console.log(e);
  } finally {
    loading.value = false;
  }
};

const handleUnbind = async () => {
  if (!form.value.tagCode) {
    ElMessage.warning('请扫描标签编号');
    return;
  }
  loading.value = true;
  try {
    const res = await unbindTag({ tagCode: form.value.tagCode });
    if (res.code === 200) {
      ElMessage.success('解绑成功');
      router.back();
    } else {
      ElMessage.warning(res.msg || '解绑失败');
    }
  } catch (e) {
    //检测异常
    console.log(e);
  } finally {
    loading.value = false;
  }
};

function onProjectChange(val: string | number) {
  const selected = projectOptions.value.find((item) => item.value === val);
  form.value.projectId = selected ? selected.value : '';
  form.value.projectCode = selected ? selected.label : '';
}
// 监听车列、车辆、项目号变化，自动拼接vehicleCode、vehicleColumn、vehicleNumber、wbsCode
watch([() => form.value.vehicleColumn, () => form.value.vehicleNumber, () => form.value.projectCode], () => {
  form.value.vehicleCode = `${form.value.vehicleColumn}-${form.value.vehicleNumber}`;
  form.value.wbsCode = `A-${form.value.projectCode}-P-${form.value.vehicleColumn}-${form.value.vehicleNumber}`;
});

// 轮询定时器，用于定时调用readRfid方法
let pollingTimer: ReturnType<typeof setTimeout> | null = null;
// 超时定时器，用于限制扫描最长等待时间
let scanTimeout: ReturnType<typeof setTimeout> | null = null;
// 轮询间隔（毫秒），每隔1秒轮询一次
const POLL_INTERVAL = 1000; // 1秒轮询
// 扫描超时时间（毫秒），10秒未读到卡则超时
const SCAN_TIMEOUT = 10000; // 10秒超时
/**
 * 处理原生(Android)回调消息
 * @param jsonData 原生传递的JSON字符串，包含标签信息
 * 成功解析后会停止轮询和超时定时器，并将标签号写入表单
 */
function handleNativeMessage(jsonData: string) {
  try {
    // ElMessage.success("jsonData:" + jsonData);
    const data = JSON.parse(jsonData);
    form.value.tagCode = data[1];
    stopPolling(); // 读到卡后停止所有定时器
    scanLoading.value = false;
    scanDisabled.value = false;
    if (window.Android && typeof window.Android.stopRead === 'function') {
      window.Android.stopRead();
    }
    ElMessage.success('标签扫描成功');
    afterScanTag();
  } catch (e) {
    console.error('[调试] 解析原生消息失败:', e, jsonData);
    stopPolling();
    scanLoading.value = false;
    scanDisabled.value = false;
    ElMessage.error('标签解析失败');
  }
}
/**
 * 轮询调用Android的readRfid方法，持续尝试读取标签
 * 直到读到卡（收到原生回调）或超时
 */
function pollRfid() {
  if (window.Android && typeof window.Android.readRfid === 'function') {
    window.Android.readRfid();
    pollingTimer = setTimeout(pollRfid, POLL_INTERVAL);
  }
}
/**
 * 停止轮询和超时定时器，防止内存泄漏
 * 在读到卡、超时或组件卸载时调用
 */
function stopPolling() {
  if (pollingTimer) {
    clearTimeout(pollingTimer);
    pollingTimer = null;
  }
  if (scanTimeout) {
    clearTimeout(scanTimeout);
    scanTimeout = null;
  }
}
/**
 * 扫描标签主入口，点击“扫描标签”按钮时触发
 * 启动Android读卡并开始轮询，设置超时保护
 * 非Android环境下模拟标签号
 */
function scanTag() {
  if (scanDisabled.value) return;

  scanLoading.value = true;
  scanDisabled.value = true;

  if (window.Android && typeof window.Android.startRead === 'function') {
    window.Android.startRead();
    pollRfid(); // 启动轮询

    // 超时处理，10秒未读到卡则自动停止
    scanTimeout = setTimeout(() => {
      stopPolling();
      scanLoading.value = false;
      scanDisabled.value = false;
      if (window.Android && typeof window.Android.stopRead === 'function') {
        window.Android.stopRead();
      }
      ElMessage.warning('未检测到标签，请重试');
    }, SCAN_TIMEOUT);
  } else {
    // 非Android环境模拟
    form.value.tagCode = 'MOCK_TAG_' + Math.floor(Math.random() * 1000000);
    scanLoading.value = false;
    scanDisabled.value = false;
    ElMessage.success('标签扫描成功(未处于Android环境)');
  }
}

// 自动查项目（扫描到标签后调用）
async function afterScanTag() {
  if (form.value.tagCode) {
    try {
      const res = await getTagProject(form.value.tagCode);
      if (res.code === 200 && res.data) {
        // 字段映射关系
        const map = {
          id: 'id',
          tagCode: 'tagCode',
          bindTargetType: 'bindTargetType',
          projectCode: 'projectCode',
          projectId: 'projectId',
          vehicleCode: 'vehicleCode',
          vehicleColumn: 'vehicleColumn',
          vehicleNumber: 'vehicleNumber',
          wbsCode: 'wbsCode',
          tagLocation: 'tagPosition', // 后端->前端
          vehicleType: 'carriageTypeId', // 后端->前端
          carHeadOrientation: 'carPositions', // 后端->前端
          moveTheCar: 'moveTheCar' // 可能后端无此字段
        };
        // 自动填充表单
        Object.keys(map).forEach((key) => {
          if (res.data[key] !== undefined && map[key] in form.value) {
            form.value[map[key]] = res.data[key];
          }
        });
        ElMessage.warning('该标签已绑定wbs：' + (res.data.wbsCode || ''));
        if (isUnbind.value) showDetailForm.value = true;
      }
    } catch (e) {
      // 忽略未绑定项目的报错
    }
  }
}

let inactivityTimer: ReturnType<typeof setTimeout> | null = null;
const INACTIVITY_LIMIT = 5 * 60 * 1000;

function resetInactivityTimer() {
  if (inactivityTimer) clearTimeout(inactivityTimer);
  inactivityTimer = setTimeout(() => {
    ElMessage.warning('长时间无操作，已自动返回上一页');
    router.back();
  }, INACTIVITY_LIMIT);
}

function addInactivityListeners() {
  const events = ['click', 'touchstart', 'keydown'];
  events.forEach((event) => {
    window.addEventListener(event, resetInactivityTimer, true);
  });
}

function removeInactivityListeners() {
  const events = ['click', 'touchstart', 'keydown'];
  events.forEach((event) => {
    window.removeEventListener(event, resetInactivityTimer, true);
  });
}

// 在组件挂载时注册原生回调、初始化硬件、监听用户操作
onMounted(() => {
  // 不再需要loadProjectDict
  window.callJsFunction = handleNativeMessage;
  if (window.Android && typeof window.Android.powerOn === 'function') {
    window.Android.powerOn();
  }
  addInactivityListeners();
  resetInactivityTimer();
});
// 在组件卸载时清理定时器、释放硬件、注销回调
onUnmounted(() => {
  stopPolling();
  if (window.Android && typeof window.Android.powerOff === 'function') {
    window.Android.powerOff();
  }
  window.callJsFunction = undefined;
  if (inactivityTimer) clearTimeout(inactivityTimer);
  removeInactivityListeners();
});
</script>

<style lang="scss" scoped>
.tag-bind-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #f5f5f5;
  // max-width: 800px;
  // margin: 0 auto;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #409eff;
    color: white;
    font-size: 18px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .back-icon {
      font-size: 24px;
      cursor: pointer;
    }
  }

  .form-container {
    // flex: 1;
    overflow-y: auto;
    padding: 15px;
    height: calc(100% - 108px);

    .bind-form {
      height: 100%;
      display: flex;
      flex-direction: column;
      gap: 20px;
      overflow: auto;

      .full-width {
        width: 100%;
      }
    }
  }

  .button-container {
    display: flex;
    flex-direction: row;
    gap: 16px;
    margin-top: 32px;
    margin-bottom: 16px;
    justify-content: center;
    align-items: center;
    padding: 0 10px;

    .scan-button,
    .submit-button {
      width: 48%;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
      border-radius: 24px;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
      transition: background 0.2s, box-shadow 0.2s;
    }

    .scan-button {
      background: #fff;
      color: #409eff;
      border: 1.5px solid #409eff;
    }

    .scan-button:hover {
      background: #ecf5ff;
      color: #1867c0;
      border-color: #1867c0;
    }

    .submit-button {
      background: #409eff;
      color: #fff;
      border: none;
    }

    .submit-button:hover {
      background: #1867c0;
      color: #fff;
    }
  }
}

:deep(.radio-container) {
  .el-form-item__content {
    flex-wrap: nowrap !important;

    .el-radio-group {
      flex-wrap: nowrap !important;

      .el-radio {
        margin-right: 0px !important;
      }
    }
  }
}

.carriage-type-row {
  display: none;
}
</style>
